﻿function showExperimentList() {
	if (refreshTab('showExperimentList'))
		return;
	var pageSize = 20;
	var showPreview = window.screen.width > 800;

	var store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : url.getExperimentList
						}),
				reader : new Ext.data.JsonReader({
							root : 'result',
							totalProperty : 'total',
							id : 'eid'
						}, ['eid', 'title', 'description', 'status',
								'startTime', 'endTime'])
			});
	store.load({
				params : {
					start : 0,
					limit : pageSize
				}
			});
    var expander = new Ext.ux.RowExpander({
        tpl : new Ext.Template(
            '<p>{description}</p><br>'
        )
    });
	var cm = new Ext.grid.ColumnModel([{
				header : 'Experiment Title',
				sortable : false,
				dataIndex : 'title',
				renderer : titleFormat
			}, {
				header : 'Deadline',
				sortable : false,
				dataIndex : 'endTime',
				width : 30,
				renderer : deadlineFormat
			}]);

	var sm = new Ext.grid.RowSelectionModel({
				singleSelect : true
			});
	var toolbar = new Ext.Toolbar({
				items : [new Ext.Button({
									text : '刷新',
									iconCls : 'refresh-icon',
									handler : function() {
										store.reload();
									}
								}), new Ext.Button({
									text : '描述',
									iconCls : 'preview-icon',
									enableToggle : true,
									pressed : showPreview,
									toggleHandler : function(sender, pressed) {
										showPreview = pressed;
										grid.view.refresh();
									}
								}), new Ext.Toolbar.Separator(),
						new Ext.Button({
									text : '查看',
									iconCls : 'problemlist-icon',
									disabled : true,
									handler : onShowExperiment
								}), new Ext.Button({
									text : '状态',
									iconCls : 'status-icon',
									disabled : true,
									handler : onStatus
								})]
			});

	var godbuttons;
	if (sys.god || sys.teacher) {
		godbuttons = [new Ext.Toolbar.Separator(), new Ext.Button({
							text : '添加实验',
							iconCls : 'add-icon',
							handler : function() {
								addOrEditExperiment();
							}
						}), new Ext.Button({
							text : '编辑实验',
							iconCls : 'edit-icon',
							handler : onEdit,
							disabled : true
						}), new Ext.Button({
							text : '删除实验',
							iconCls : 'delete-icon',
							handler : onDelete,
							disabled : true
						}), new Ext.Toolbar.Separator(), new Ext.Button({
							text : '添加班级',
							iconCls : 'addclass-icon',
							handler : function() {
								addOrEditClass();
							}
						}), new Ext.Button({
							text : '管理班级',
							iconCls : 'editclass-icon',
							handler : function() {
								selectClass(function(cid) {
											showStudentList(cid);
										});
							}
						}), new Ext.Toolbar.Separator(), new Ext.Button({
							text : '统计实验',
							iconCls : 'statistics-icon',
							handler : onStatistics,
							disabled : true
						})];
		toolbar.add(godbuttons);
	}

	var pagebar = new Ext.PagingToolbar({
				pageSize : pageSize,
				store : store,
				displayInfo : true,
				emptyMsg : '当前没有实验。',
				displayMsg : '当前显示第 {0} - {1} 个实验，共 {2} 个实验。',
				plugins : new Ext.ux.SlidingPager()
			});

	var grid = new Ext.grid.GridPanel({
				id : 'showExperimentList',
				title : 'DataStruct',
				iconCls : 'experiment-icon',
				closable : true,
				region : 'center',
				loadMask : {
					msg : '载入中...'
				},
				viewConfig : {
					forceFit : true,
					enableRowBody : true,
					showPreview : showPreview,
					getRowClass : previewFormat,
					scrollToRow : function(rowIndex) {
						var firstRow = Ext.get(this.getRow(0));
						var row = Ext.get(this.getRow(rowIndex));
						var distance = row.getOffsetsTo(firstRow)[1];
						this.scroller.dom.scrollTop = distance;
					}
				},
				store : store,
				cm : cm,
				sm : sm,
				tbar : toolbar,
				bbar : pagebar,
				plugins: expander,
		        collapsible: true,
		        animCollapse: false
			});
	sm.on('selectionchange', onSelect);
	grid.on('rowdblclick', onShowExperiment);
	grid.onRefresh = onRefresh;
	
	if(sys.dataStruct == true) return grid;
	addTab(grid);

	function onClose()
	{
		expander.collapseRow(0);
	}
	function onRefresh() {
		store.reload();
	}
	function titleFormat(value, p, record) {
		if (showPreview)
			return String
					.format(
							'<div class="{2}" style="height:16px">e{0}.&nbsp; '
									+ '<a href="javascript:void(0);" onclick="showDSProblemList({0});" class="likelink" style="color:black;font-weight:bold">{1}</a>'
									+ '<br />', record.data.eid, value,
							['problem-icon', 'solving-icon', 'accepted-icon',
									'finished-icon'][record.data.status]);
		return String
				.format(
						'<div class="{2}" style="height:16px">e{0}.&nbsp; '
								+ '<a href="javascript:void(0);" onclick="showDSProblemList({0});" class="likelink" style="color:black;font-weight:bold">{1}</a>',
						record.data.eid, value, ['problem-icon',
								'solving-icon', 'accepted-icon',
								'finished-icon'][record.data.status]);
	}
	function deadlineFormat(value, p, record) {
		if (showPreview) {
			if (Ext.isEmpty(record.data.startTime))
				return String
						.format(
								'<span class="ratio-text">{0}</span><br /><div>&nbsp;</div>',
								value);
			return String
					.format(
							'{0} ~<br /><div><span class="ratio-text">{1}</span></div>',
							record.data.startTime, value);
		}
		return String.format('<span class="ratio-text">{0}</span>', value);
	}
	function previewFormat(record, rowIndex, p) {
		if (showPreview) {
			p.body = String.format('<p>{0}</p>', Ext.util.Format
							.trim(record.data.description)
							.gbtrim(window.screen.width > 800 ? 120 : 60));
			return 'x-grid3-row-expanded';
		}
		return 'x-grid3-row-collapsed';
	}

	function onEdit() {
		var select = getSelect();
		if (!select)
			return;
		addOrEditExperiment(select.data.eid);
	}
	function onDelete() {
		var select = getSelect();
		if (!select)
			return;
		deleteExperiment({
					eid : select.data.eid,
					title : select.data.title
				});
	}

	function getSelect() {
		if (sm.getCount() == 0)
			return null;
		return sm.getSelected();
	}
	function onSelect() {
		var record = getSelect();
		var disable = !record;
		toolbar.get(3).setDisabled(disable);
		toolbar.get(4).setDisabled(disable);
		if(record){
			for(var i = 0; i < store.getCount(); ++i){
				expander.collapseRow(i);
			}
			var rowIndex = store.indexOf(record);
			if(rowIndex == -1)
			alert("false");
			expander.expandRow(rowIndex);
		}
		if (sys.god || sys.teacher) {
			godbuttons[2].setDisabled(disable);
			godbuttons[3].setDisabled(disable);
			godbuttons[8].setDisabled(disable);
		}
	}
	function onShowExperiment() {
		var record = getSelect();
		if (!record)
			return;
		showDSProblemList(record.data.eid);
	}
	function onStatistics() {
		var record = getSelect();
		if (!record)
			return;
		selectClass(function(cid) {
					showDSStatistics({
								eid : record.data.eid,
								cid : cid
							});
				});
	}
	function onStatus() {
		var record = getSelect();
		if (!record)
			return;
		showDSStatusList({
					page : 1,
					eid : record.data.eid
				});
	}
}

function deleteExperiment(obj) {
	confirmx('您确定要删除实验 '
					+ (obj.title
							? '<br />e(' + obj.eid + ') - ' + obj.title
							: ' - e(' + obj.eid + ')')
					+ ' 吗？<br />该实验的所有题目与状态也会被一并删除！', function() {
				ajax({
							url : url.deleteExperiment,
							params : {
								eid : obj.eid
							},
							success : function() {
								showExperimentList();
								if (obj.success)
									obj.success();
							}
						});
			});
}
